<?php
/**
 * User.php
 * Author: luoji (867404364@qq.com)
 * Date: 2020-12-18
 * Time: 19:18
 */

namespace App\Http\Controllers\Api;


use App\Http\Controllers\Base;
use App\Tables;
use App\Tool\RandomStr;

class User extends Base
{
    public function changePassWord()
    {
        $v = \Validator::make($this->request->post(), [
            'old' => 'required',
            'new' => 'required|same:renew',
            'renew' => 'required|same:new',
            'uid' => 'required'
        ], [
            'required' => ':attribute 不能为空',
            'same' => ':attribute 必须和 :other 一致'

        ], [
            'old' => '旧密码',
            'new' => '新密码',
            'renew' => '确认新密码'
        ]);
        if($v->fails()) {
            return $this->responseFail($v->errors()->first());
        }

        $uid = $this->request->post('uid');
        $old = $this->request->post('old');
        $new = $this->request->post('new');

        $find = Tables\Admin::where(['id' => $uid])->first();
        if(empty($find)) {
            return $this->responseFail('用户不存在！');
        }

        if($find['password'] !== md5(md5($old).md5($find['salt']))) {
            return $this->responseFail('原始密码输入错误！');
        }
        $salt = RandomStr::make();
        $nPwd = md5(md5($new).md5($salt));
        $ok = (bool) Tables\Admin::where(['id' =>  $uid])->update([
            'password' => $nPwd,
            'salt' => $salt,
        ]);
        return $ok ? $this->responseSuccess() : $this->responseFail('重置失败！');
    }
}